<script setup>

import {computed, ref} from 'vue';

import * as roleApi from '@/api/roleApi.js';
import * as userApi from '@/api/userApi.js'
import {message} from 'ant-design-vue';
import {grantToUser} from '@/api/roleApi.js';


const open = ref(false)
const grantedUsers = ref([])
const unGrantedUsers = ref([])
const loading = ref(false)
const curRoleId = ref('')

const selectUsersId = ref([])

const allUsers = ref([])

function mergeAllUsers() {
  allUsers.value = [...grantedUsers.value, ...unGrantedUsers.value]
  allUsers.value = allUsers.value.map(x => ({
    key: x.userId,
    title: x.account
  }))
}


const getGrantedUsers = async (roleId) => {
  await roleApi.fetchGrantedUsers(roleId).then(res => {
    grantedUsers.value = res
  })
}
const getUnGrantedUsers = async (roleId) => {
  await roleApi.fetchUnGrantedUsers(roleId).then(res => {
    unGrantedUsers.value = res
  })
}

const onOpen = async (roleId) => {
  if (!roleId) {
    message.error('角色id 未正确传递')
    return
  }
  await getGrantedUsers(roleId)
  await getUnGrantedUsers(roleId)
  mergeAllUsers()
  curRoleId.value = roleId
  selectUsersId.value =  grantedUsers.value.map(x => x.userId)
  open.value = true
}



const submit = () => {
  let params = {
    roleId: curRoleId.value,
    userIds: selectUsersId.value
  }
  loading.value = true
  grantToUser(params).then(res => {
    message.success('角色分配成功')
  }).finally(() => loading.value = false)
}

const onClose = () => {
  open.value = false
}

defineExpose({
  onOpen
})


</script>

<template>

  <a-drawer
      title="角色分配"
      :width="600"
      :open="open"
      @close="onClose"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
  >

      <a-transfer
          v-model:target-keys="selectUsersId"
          :data-source="allUsers"
          :one-way="true"
          :titles="['未分配用户', '已分配用户']"
          :render="item => item.title"
      />


    <template #footer>
      <a-space>
        <a-button @click="onClose">关闭</a-button>
        <a-button :loading="loading" type="primary" @click="submit">提交</a-button>
      </a-space>
    </template>

  </a-drawer>

</template>

<style scoped>
.tree-transfer .ant-transfer-list:first-child {
  width: 50%;
  flex: none;
}
</style>
